package com.cn.wanix.filter;

import com.alibaba.fastjson.JSON;
import com.cn.wanix.model.ResultModel;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {
    /**
     * servlet的生命周期？
     * init
     * service
     * destroy
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
// 只运行一次 ，项目启动的时候

    }

    /**
     * 拦截所有进入后台的请求地址
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //        0.乱码处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String path = req.getServletPath();
        System.out.println(path);
        if(path.startsWith("/back/")){
            //        判断是否已经登陆，如果登录则放行，可以操作后台数据，
//        不放行，则直接返回一条数据，提示用户需要登陆
            String username = (String) req.getSession().getAttribute("username");
            boolean isLogin = username == null;
            if (isLogin) {
                ResultModel resultModel = new ResultModel(-1, "未登录");
                String resJSON = JSON.toJSONString(resultModel);     // 转换为json
                resp.getWriter().print(resJSON); // 输出
                return;
            }
            filterChain.doFilter(req, resp);
        }else {
            filterChain.doFilter(req, resp);
        }
    }

    @Override
    public void destroy() {

    }
}
